package com.cxx.purchasecharge.component.utils;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.WebRequest;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.LoginUser;
import com.cxx.purchasecharge.component.bean.PCApplicationContext;

public class AjaxUtils
{
    private static final Logger logger = Logger.getLogger (AjaxUtils.class);

    private AjaxUtils ()
    {
    }

    public static boolean isAjaxRequest (WebRequest webRequest)
    {
        String requestedWith = webRequest.getHeader ("X-Requested-With");
        return requestedWith != null ? "XMLHttpRequest".equals (requestedWith) : false;
    }

    public static boolean isAjaxUploadRequest (WebRequest webRequest)
    {
        return webRequest.getParameter ("ajaxUpload") != null;
    }

    public static String getJsonObject (ActionResult actionResult)
    {
        JSONObject jsonObject = JSONObject.fromObject (actionResult);
        return jsonObject.toString ();
    }

    @SuppressWarnings ("rawtypes")
    public static String getJsonArray (List list)
    {
        JSONArray jsonArray = JSONArray.fromObject (list);
        return jsonArray.toString ();
    }
    
    public static String getUserIdFromRequest (PCApplicationContext pcContext, HttpServletRequest request) 
    {
        String userId = null;
        LoginUser loginUser;
        try
        {
            loginUser = pcContext.getLoginUser (request);
            userId = loginUser.getUserId ();
        }
        catch (Exception e)
        {
            logger.warn("getUserIdFromRequest failed", e);
        }
        return userId;
    }

}